import 'package:flutter/material.dart';

import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

import 'widget/input_item.dart';

class BindingAccountPage extends StatefulWidget {
  const BindingAccountPage({super.key, this.thirdPartyUserId});
  final int? thirdPartyUserId;

  @override
  State<BindingAccountPage> createState() => _BindingAccountPageState();
}

class _BindingAccountPageState extends State<BindingAccountPage> {
  TextEditingController usernameController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  FocusNode usernameFocusNode = FocusNode();
  FocusNode codeFocusNode = FocusNode();
  bool submitting = false;
  bool isAgree = false;
  bool isShowVerifyLogin = false;
  bool isReady = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    usernameFocusNode.unfocus();
    codeFocusNode.unfocus();
    super.dispose();
  }

  /// 提交登录
  submitLogin() async {
    if (usernameController.text == '') {
      return Ui.toast('请先输入手机号码');
    }
    if (codeController.text == '') {
      return Ui.toast('请先输入验证码');
    }
    setState(() {
      submitting = true;
    });
    usernameFocusNode.unfocus();
    codeFocusNode.unfocus();
    var res = await Http.instance
        .post('/api/user/public/verificationCodeLogin', data: {
      'username': usernameController.text,
      'third_party_user_id': widget.thirdPartyUserId,
      'verification_code': codeController.text,
    });

    if (res.code == 1) {
      Get.back(result: await AuthService.instance.login(res.data['token']));
    } else {
      setState(() {
        submitting = false;
      });
      Ui.toast(res.msg);
    }
  }

  bool get isAlreadyToLogin =>
      usernameController.text.isNotEmpty && codeController.text.isNotEmpty;
  @override
  Widget build(BuildContext context) {
    Ui.onPageAnimateCompleted(context, () {
      setState(() {
        isReady = true;
      });
    });
    return Scaffold(
      appBar: AppBar(
        backgroundColor: UiTheme.of(context)
            .matchColor(Colors.white, Colors.black)
            .withOpacity(0),
      ),
      body: AnimatedSwitcher(
        duration: kThemeAnimationDuration,
        child: isShowVerifyLogin
            ? Container()
            : SingleChildScrollView(
                padding: const EdgeInsets.all(25),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Bind mobile phone number'.tr,
                      style: const TextStyle(
                          fontSize: 20, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 5),
                    const Text(
                      '为防止帐号丢失以及方便找回，建议你绑定手机号码后再使用',
                      style: TextStyle(
                        color: Colors.black45,
                      ),
                    ),
                    const SizedBox(height: 30),
                    InputItemView(
                      render: isReady,
                      controller: usernameController,
                      focusNode: usernameFocusNode,
                      placeholder: '请输入手机号码',
                      onChanged: (value) {
                        setState(() {
                          isAlreadyToLogin;
                        });
                      },
                      icon: UiIcons.mobile,
                    ),
                    InputItemView(
                      render: isReady,
                      controller: codeController,
                      focusNode: codeFocusNode,
                      placeholder: '请输入验证码',
                      maxLength: 6,
                      keyboardType: TextInputType.number,
                      onChanged: (value) {
                        setState(() {
                          isAlreadyToLogin;
                        });
                      },
                      icon: UiIcons.safetycertificate,
                      suffix: UiVerificationCode(
                        account: () => usernameController.text,
                      ),
                    ),
                    const SizedBox(height: 20),
                    SizedBox(
                      width: double.infinity,
                      height: UiTheme.buttonHeight,
                      child: UiButton(
                        onPressed: submitLogin,
                        loading: submitting,
                        disabled: !isAlreadyToLogin,
                        child: Text(
                          '完成'.tr,
                          style: const TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
      ),
    );
  }
}
